// @flow
import React, { Component } from 'react'
import styles from './RolesAdd.css'
import { Form, Input, Button, message, Tree } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
const TreeNode = Tree.TreeNode

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}
type Props = {
  form: Object,
  history: Object
}

type States = {
  loading: boolean,
  defaultExpandAll: boolean,
  menus: Array<Object>,
  expandedKeys: Array<string>,
  autoExpandParent: boolean,
  checkedKeys: Array<Object>,
  selectedKeys: Array<Object>
}
class RolesAdd extends Component {
  props: Props
  state: States
  submit: Function
  goBack: Function
  getMenus: Function
  initChildren: Function
  onExpand: Function
  onCheck: Function
  onSelect: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      loading: false,
      menus: [],
      expandedKeys: [],
      autoExpandParent: false,
      checkedKeys: [],
      selectedKeys: [],
      defaultExpandAll: true
    }
    this.submit = this.submit.bind(this)
    this.goBack = this.goBack.bind(this)
    this.getMenus = this.getMenus.bind(this)
    this.onExpand = this.onExpand.bind(this)
    this.onCheck = this.onCheck.bind(this)
    this.onSelect = this.onSelect.bind(this)
  }

  componentWillMount () {
    this.getMenus()
  }

  onCheck (checkedKeys) {
    this.setState({
      'checkedKeys': checkedKeys,
      'selectedKeys': []
    })
  }
  onSelect (checkedKeys, info) {
    this.setState({ checkedKeys })
  }
  onExpand (expandedKeys) {
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
    this.setState({
      'expandedKeys': expandedKeys,
      'autoExpandParent': false
    })
  }
  initChildren (object) {
    if (object.children) {
      if (object.children) {
        let expandedKeys1 = this.state.expandedKeys
        let key1 = object.key + ''
        expandedKeys1.push(key1)
        this.setState({
          'expandedKeys': expandedKeys1
        })
      }
      const children = object.children.map((data, index) => {
        let data1 = {}
        data1['key'] = data.id
        data1['title'] = data.name
        if (data.children.length > 0) {
          data1['children'] = data.children
        }
        this.initChildren(data1)
        return data1
      })
      object['children'] = children
    }
  }
  getMenus () {
    universalFetch(`${__SERVICE_API__}sys/menus?isTree=true`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        this.setState({
          menus:result.map((data, index) => {
            const data1 = {}
            data1['key'] = data.id
            data1['title'] = data.name
            data1['children'] = data.children
            this.initChildren(data1)
            return data1
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  submit () {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const values = {
        ...fieldsValue
      }
      values.menuIds = this.state.checkedKeys
      universalFetch(`${__SERVICE_API__}sys/roles`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify(values)
      })
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(json.message, 'RolesAdd.js')
          }
          this.setState({
            loading: false
          })
          message.success('添加成功')
          this.props.history.push('/system/roleSetting')
        })
        .catch((err) => {
          console.error(err)
          message.error('添加失败')
          this.setState({
            loading: false
          })
        })
    })
  }

  goBack () {
    this.props.history.push('/system/roleSetting')
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { loading, menus } = this.state
    const loop = data => data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.key} title={item.title}>
            {loop(item.children)}
          </TreeNode>
        )
      }
      return <TreeNode key={item.key} title={item.title} />
    })
    return (
      <div className={styles['main']}>
        <Form>
          <FormItem {...formItemLayout} label='名称' hasFeedback>
            {
              getFieldDecorator('name', {
                rules: [
                  { required: true, message: '请填写名称', whitespace: true }
                ]
              })(
                <Input placeholder='请填写名称' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='英文名称' hasFeedback>
            {
              getFieldDecorator('enname', {
                rules: [
                  { required: true, message: '请填写英文名称', whitespace: true }
                ]
              })(
                <Input placeholder='请填写英文名称' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='操作菜单' hasFeedback>
            {
              getFieldDecorator('menus', {
                rules: [
                  { required: false, message: '请填写菜单id,逗号分割' }
                ]
              })(
                <Tree
                  checkable
                  defaultExpandAll={this.state.defaultExpandAll}
                  onExpand={this.onExpand}
                  expandedKeys={this.state.expandedKeys}
                  autoExpandParent={this.state.autoExpandParent}
                  onCheck={this.onCheck}
                  // checkedKeys={this.state.checkedKeys}
                  onSelect={this.onSelect}
                  // selectedKeys={this.state.selectedKeys}
               >
                  {loop(menus)}
                </Tree>
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary'
              loading={loading}
              onClick={this.submit}
              >
              保存
            </Button>
            <Button
              onClick={this.goBack}
              style={{ marginLeft: '20px' }}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

export default Form.create()(RolesAdd)
